var _ = require('lodash'),
    GamePost = require('./gamePost.model'),
    im = require('immutable'),
    faker = require('faker'),
    _debug = require('debug');

const DEFAULT_PAGESIZE = 10,
    MIN_PAGESIZE = 5,
    MAX_PAGESIZE = 25;

const debug = _debug('app:server:API_of_GamePosts')

exports.index = function(req, res) {
    // if(req.query.page && req.query.page < 1) return res.status(400).send('Invalid page');

    // Parse the page size that client pass in
    var pageSize = (req.query.pagesize && req.query.pagesize <= MAX_PAGESIZE && req.query.pagesize > MIN_PAGESIZE) ? req.query.pagesize : DEFAULT_PAGESIZE;
    var page = parseInt(req.query.page) || 0;
    if (page < 1) page = 1;

    GamePost.count({}, function(err, count) {
        if (err) res.status(500).json(err)
        var query;
        query = GamePost.find();
        query
            .limit(pageSize)
            .sort('date')
            .skip((page-1) * pageSize || 0)//doesn't scale well, I'll worry about it later
            .exec(function(err, gamePosts) {
                if (err) res.status(500).json(err)
                setTimeout(function() {
                    return res.status(200).json({
                            page: page,
                            pages: Math.ceil(count / pageSize),
                            items: gamePosts,
                            numItems: count
                         });
                },200);  // Mock Latency for 200 ms.

            });
    });
};

/**
 * Creates a new gamePost
 */
export function create(req, res, next) {

    var gamePostToCreate = new GamePost(req.body);
    gamePostToCreate.save(function (err, doc) {
      if (err) res.status(500).json(err)
      debug('New GamePost saved successfully.')
      res.status(200).json(doc)
    }) 
}


/**
 * get GamePost By ID
 */
export function getGamePostByID(req, res, next) {

    GamePost.findById(req.query.post_id, function (err, doc) {
        if (err) {
            res.status(500).json(err)
        }else{
            res.status(200).json(doc)
        }
    })
}




exports.faker = function(req, res) {
    
    var fakeItems = im.Range(1,100)
      .map( () => { 
        return new GamePost({ title: faker.name.findName() });
      });

    GamePost.insertMany(fakeItems, function(error, docs) {

        if (error) {
            return res.status(400).json({
                error_info: error,
            });
        } else {
            console.info('%d items were successfully stored.', docs.length);
            return res.status(200).json({
                items: fakeItems,
            });
        }
    });
};
